﻿const express = require('express')
const fs = require('fs')
const path = require('path')
const TextToSVG = require('text-to-svg')
const router = express.Router()

router.get('/family', (req, res) => {
	let filePath = path.resolve('./font')
	let list = [];
	fs.readdir(filePath,function(err,files){
        if(err){
            console.log(err)
        }else{
            //遍历读取到的文件列表
            files.forEach(function(filename){
				//获取当前文件名
				let textToSVG = TextToSVG.loadSync('./font/' + filename)// 字体设置
				let name = filename.split('.ttf')[0]
				let box = textToSVG.getMetrics(name, {anchor: 'top'})
				let svg = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" preserveAspectRatio="xMinYMin meet" width="100%" height="100%" viewbox="0 0 ${box.width} ${box.height}">`
				svg += textToSVG.getPath(name, {anchor: 'top', attributes: { transform: 'translate(0, 0)'}})
				svg += '</svg>'
				list.push({name, svg})
            });
        }
		res.send(list)
    });
})
// 计算一行文字个数	
/**
 * 
 * @param {*} str 一段文字
 * @param {*} width 总宽度
 * @param {*} size 文字大小
 */
function count ({str, width, size, spacing}) {
	let num = Math.ceil(width / (size + spacing) ) || 1;
	console.log(num, '行的个数')
	let len = str.length;
	let arr = [];
	let arr1 = str.split('')
	if (len > num) {
		let total = Math.floor(len / num)
		for (let i = 0 ; i <= total; i++) {
			let s = arr1.splice(0, num).join('');
			arr.push(s)
		}
		return arr
	} else {
		arr.push(str)
		return arr
	}
}
// 生成path方法
function production ({arr, textToSVG, size, spacing, itailic, bold, fill, underline}) {
	var path = '';
	for (let i = 0,len = arr.length; i < len; i++) {
		let options = {
			fontSize: size, // 文字大小
			anchor: 'top', // 对齐方式
			attributes: {
				transform: `translate(${(size + spacing) * i }, 0) ${itailic}`,
				'stroke-width': bold == 1 ? 1 : 0,
				'stroke-linecap': 'round',
				'stroke-linejoin': 'round',
			}
		}
		path += textToSVG.getPath(arr[i], options)
		if (underline && arr[i] != '\n') {
			path += `<line x1="${(size + spacing) * i }" x2="${(i + 1) * (size + spacing)}" y1="${size}" y2="${size}" stroke-width="4"></line>`
		}
	}
	return path
}
router.post('/', (req, res) => {
	let obj = JSON.parse(req.body.obj)
	if(obj == '') return res.send('传输为空')
	//console.log(obj)
	let family = obj.family || 'STXINWEI';
	let size = obj.size;
	let align = 'top ' + obj.align || 'left';
	let arrList = obj.arrList;
	let spacing = obj.spacing || 0;
	let line = obj.line || 0;
	let itailic = obj.itailic == 1 ? 'translate(15,0) skewX(-15)' : '';
	let bold = obj.bold
	let underline = obj.underline;
	let fill = obj.fill || '#000';
//console.log(line)
	
	// 初始化pathAPI
	let textToSVG = TextToSVG.loadSync('./font/' + family + '.ttf')// 字体设置
	// 返回的path字符串
	let svg = '', maxX = 0, width = 0, height = 0;
	let attributes = {
		transform: `${itailic}`,
		'stroke-width': bold,
		'stroke-linecap': 'round',
		'stroke-linejoin': 'round',
	}
	arrList.forEach((item, i)=> {
		let path= textToSVG.getPath(item,{fontSize: size, anchor: align, letterSpacing: spacing, attributes})
		let box = textToSVG.getMetrics(item,{fontSize: size, anchor: align, letterSpacing: spacing, attributes})
		if (underline) {
			path += `<line x1="${box.x}" x2="${box.width + box.x}" y1="${box.height}" y2="${box.height}" stroke-width="2"></line>`
		}
		//console.log(box)
		maxX < Math.abs(box.x) ? maxX = Math.abs(box.x) : maxX;
		let g = `<g transform='translate(${maxX},${(size + line * size) * i})'>`
		g += path + '</g>'
		svg += g
		width = width < box.width ? width = box.width : width;
		height += box.height + line * size

	})
	res.send({svg, width, height})
})

module.exports = router;

